import {
    Interceptor
} from './Interceptor';
import {
    getCurrentEnvironment
} from '../getBrowser'
import {
    deepObjectMerge,
    _checkIsPromise
} from '../util'
import {
    xhrGet,
    xhrPost
} from './request/xhr'
import {
    fetchPost,
    fectGet
} from './request/fetch';
// import {
//     httpGet,
//     httpPost
// } from './request/nodeHttp'
const noonFunc = () => {}
export class Http extends Interceptor {
    constructor(options) {
        super();
        // const { baseURL } = options;
        this.defaultConf = {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            timeout: 5000,	
            baseURL: ''
        }
        this.interceptors = {
                request: {
                    use: this.beforRequest.bind(this),
                    success: undefined,
                    fail: undefined
                },
                response: {
                    use: this.beforeResponse.bind(this),
                    success: undefined,
                    fail: undefined
                }
            },
            this.runType = getCurrentEnvironment()
    }
    setRunType(e) {
        let type
        if (e) {
            type = e
        } else {
            type = getCurrentEnvironment()
        }
        return this.runType = type
    }
    beforRequest(resolveFun = noonFunc(), rejectFun = noonFunc()) {
        this.interceptors.request.success = (config) => {
            return resolveFun(config)
        }
        this.interceptors.request.fail = (config) => {
            return rejectFun(config)
        }
    }
    beforeResponse(resolveFun = noonFunc(), rejectFun = noonFunc()) {
        this.interceptors.response.success = (response) => {
            return resolveFun(response)
        }
        this.interceptors.response.fail = (error) => {
            return rejectFun(error)
        }
    }
    setDefaultConfig(params) {
        this.defaultConf = deepObjectMerge(this.defaultConf, params)
        return this.defaultConf
    }
    setRequestConfig(params) {
        // debugger
        let defaultConfig = JSON.parse(JSON.stringify(this.defaultConf))
        params = deepObjectMerge(defaultConfig, params)
        return params
    }

    // setBaseURL(baseURL = '') {
    //     this.defaultConf.baseURL = baseURL
    //     return this
    // }
    // setRequestHeader(headers = {}) {
    //     Object.keys(headers).map(name => {
    //         this.httpRequest.setRequestHeader(name, headers[name])
    //     })
    //     return this
    // }
    // setRequestTimeout(timeout = 5000) {
    //     this.httpRequest.timeout = timeout
    // }


    /**
     * post put 请求方式
     * **/

    paramByBody(config) {
        return new Promise((resolve, reject) => {
            let responseData = {}

            try {
                switch (this.runType) {
                    case 'xhr':
                        responseData = xhrPost(config)
                        break;
                    case 'fetch':
                        responseData = fetchPost(config)
                        break;
                        // case 'http':
                        //     responseData = httpPost(mergeConfig)
                        //     break;
                    default:
                        responseData = xhrPost(config)
                        break
                }
                resolve(responseData)
            } catch (error) {
                reject(error)
            }
        }).then(res => {
            try {
                if (typeof this.interceptors.response.success === 'function') {
                    return this.interceptors.response.success(res);
                } else {
                    return res
                }

            } catch (e) {
                throw e;
            }
        }).catch(err => {
            console.log(err)
            if (typeof this.interceptors.response.success === 'function') {
                throw this.interceptors.response.fail(err)
            } else {
                throw err
            }

        })
    }

    /**
     * get delet 请求方式
     * **/
    parmByUrl(config) {
        return new Promise(async (resolve, reject) => {
            let responseData = {}
            console.log(this.runType)
            try {
                switch (this.runType) {
                    case 'xhr':
                        responseData = await xhrGet(config)
                        break;
                    case 'fetch':
                        responseData = await fectGet(config)
                        break;
                        // case 'http':
                        //     responseData = httpGet(config)
                        //     break;
                    default:
                        responseData = await xhrGet(config)
                        break
                }
                resolve(responseData)
            } catch (error) {
                reject(error)
            }
        }).then(res => {
            try {
                if (typeof this.interceptors.response.success === 'function') {
                    return this.interceptors.response.success(res);
                } else {
                    return res
                }

            } catch (e) {
                throw e;
            }
        }).catch(err => {
            console.log(err)
            if (typeof this.interceptors.response.success === 'function') {
                throw this.interceptors.response.fail(err)
            } else {
                throw err
            }

        })
    }



    async get(url = '', data = {}, config = {}) {
        config.url = url
        config.data = data
        config.method = 'GET'
        console.log(config)
        let mergeConfig = this.setRequestConfig(config)
        // debugger
        if (typeof this.interceptors.request.success === 'function') {
            config = await this.interceptors.request.success(mergeConfig)
        } else {
            config = mergeConfig
        }
        return this.parmByUrl(mergeConfig)
    }
    async delete(url = '', data = {}, config = {}) {
        config.url = url
        config.data = data
        config.method = 'DELETE'
        console.log(config)
        let mergeConfig = this.setRequestConfig(config)
        // debugger
        if (typeof this.interceptors.request.success === 'function') {
            config = await this.interceptors.request.success(mergeConfig)
        } else {
            config = mergeConfig
        }
        return this.parmByUrl(mergeConfig)
    }
    async post(url = '', data = {}, config = {}) {
        config.url = url
        config.data = data
        config.method = "POST"
        console.log(config)
        let mergeConfig = this.setRequestConfig(config)
        // debugger
        if (typeof this.interceptors.request.success === 'function') {
            config = await this.interceptors.request.success(mergeConfig)
        } else {
            config = mergeConfig
        }
        return this.paramByBody(config)
    }
    async put(url = '', data = {}, config = {}) {
        config.url = url
        config.data = data
        config.method = "PUT"
        console.log(config)
        let mergeConfig = this.setRequestConfig(config)
        // debugger
        if (typeof this.interceptors.request.success === 'function') {
            config = await this.interceptors.request.success(mergeConfig)
        } else {
            config = mergeConfig
        }
        return this.paramByBody(config)
    }
}